export let CommonCurdDialgMixin = {
  props: {
    isEdit: false,
    row: null,
    def: null,
    columDefMap: null,
    columns: null,
    columnKey: null
  },
  computed: {
    columnKeys() {
      // console.log('columns', this.columns)
      if (!Array.isArray(this.columns)) {
        return []
      }
      return this.columns.map(v =>v.prop) ?? []
    },
    columnMap() {
      let obj = {}
      if (!Array.isArray(this.columns)) {
        return obj
      }
      this.columns.forEach(column => {
        obj[column.prop] = column
      })
      return obj
    }
  },
  methods: {
    findColumnDefByKey(key, path) {
      let column = this.columns.find(v => v.prop === key)
      if (column) {
        return ZY.lodash.get(column, path)
      }
      return ''
    }
  }
}

/**
 *
 * @param cached
 * @returns {{mixins: {methods: {}, props: {def: null, isEdit: boolean, columns: null, index: null, row: null, columnKey: null, columDefMap: null}}[], data(): {formConfigLoaded: boolean}, created(): void, methods: {handleFormInitReady(): void, private__sendCancel(): void, defFormControl(*): *&{onFire(*): void}, handleDefaultOnFire([*,*,*]=): void, private__sendConfirm(): void}}|{formConfigLoaded: boolean}|(*&{onFire(*): void})}
 */
export let createCurdDialogMixin = function ({cached = true} ={}) {
  let id = ZY.rid()
  let tasks = []
  let curFormDef = null
  let loaded = false
  let now = 1
  let cachedF = null

  return {
    mixins: [
      CommonCurdDialgMixin
    ],
    data() {
      return {
        curFormCtx: null,
        formConfigLoaded: false,
      }
    },
    async created() {
      // console.log('tasks', tasks, formDefs)
      if (!loaded) {
        if (tasks.length > 0) {
          let results = await Promise.all(tasks)

          loaded = true
          // console.log(results)

          results.forEach(({id, res}) => {
            if (curFormDef) {
              curFormDef.def = res.result
              cachedF = ZY.JSON5.parse(ZY.JSON5.stringify(res.result))
            }
            // console.log(formDef)
          })
        }
        this.formConfigLoaded = true
      } else {
        // curFormDef.def = cachedF
        // await ZY.sleep(1000)
        // console.log(curFormDef)
        this.formConfigLoaded = true
      }
    },
    methods: {
      defFormControl(formDef, {request = globalThis.Req} = {}) {

        let self = this
        // console.log(curFormDef)
        if (cached && loaded) {
          let s = {
            ...formDef,
            onFire(opt) {
              // console.log(type, args, ctx)
              self.handleDefaultOnFire(opt)
            }
          }
          s.def = cachedF
          return s
        }

        if (formDef.defUrl) {
          tasks.push(new Promise(async (resolve) => {
            let [err, res] = await ZY.awaitTo(request.get(formDef.defUrl))
            if (!err) {
              resolve({id, res})
            }
          }))
        }
        let ret = {
          ...formDef,
          onFire(opt) {
            // console.log(type, args, ctx)
            self.handleDefaultOnFire(opt)
          }
        }
        // formDefs.set(id, ret)
        curFormDef = ret
        // console.log(curFormDef)

        return ret
      },
      handleFormInitReady({ctx}) {
        this.curFormCtx = ctx
        if (this.isEdit) {
          // console.log(this.$refs.controlForm.getCurForm())
          let form = ctx.getCurForm()
          console.log(form, this.row)
          if (form) {
            form.importData(this.row)
          }
        }
      },
      handleDefaultOnFire([type, args, ctx] = []) {
        let self = this
        if (type === 'edit-form-submit') {
          self.private__sendConfirm()
        } else if (type === 'edit-cancel') {
          self.private__sendCancel()
        }
      },
      async private__sendConfirm() {
        let refDom = this.curFormCtx
        if (!refDom || !refDom.getCurForm) {
          // console.log('this.$refs[ref]', this.curFormCtx, ref)
          return
        }
        let form = refDom.getCurForm()
        // console.log('form', form)
        if (form) {
          let ret = {}
          // form.submit().then(res => {
          //   console.log(res)
          // })

          let [err, [isValid]] = await ZY.awaitTo(form.submit())

          if (isValid) {
            if (form) {
              ret.data = form.getCloneData()
            }
            if (this.isEdit) {
              ret.id = ret.data[this.columnKey]
            }

            this.$emit('confirm', ret)
          }
        }
      },
      private__sendCancel() {
        this.$emit('cancel', {
        })
      }
    }
  }
}
